<template>
  <div class="order">
      <!-- 提示信息 -->
      <van-notice-bar
        text="以下是订单详情,确认完购买课时数量并支付后分享可以获取优惠券哦，快加入女王健身吧..."
        left-icon="../static/voice.png"
        />
      <!-- 订单详细 -->
      <div class="">
          <van-cell-group class="order-form">
            <van-cell class="order-field" icon="records" :value="course.name" title="课程:"/>
            <van-field class="order-field" left-icon="cart" type="number" @blur="checkCount" placeholder="请输入购买数量" v-model="count" label="购买课时:"/>
            <van-cell class="order-field" icon="location" :value="course.address" title="地点:" type="textarea" rows="1"/>
            <!-- <div class="van-cell van-hairline van-field order-field">
                <div class="van-cell__title"><span>人数:</span></div>
                <van-stepper class="person-step"
                    v-model="person_num"
                    integer
                    :min="1"
                    :max="40"
                    :step="1"
                    :default-value="1"
                />
            </div> -->
            <van-cell class="order-field" icon="exchange" :value="origin_price + '元'" title="单价:"/>
            <van-cell class="order-field" icon="gold-coin" :value="origin_price * count + '元'" title="总价:"/>
            <!-- 优惠说明 -->
            <!-- <div class="van-cell van-hairline van-field order-field">
                <div class="van-cell__title">
                    <span>折后价:</span>
                </div>
                <div class="van-cell__value">
                    <input v-model="price_discount" type="input" class="van-field__control">
                </div>
            </div> -->
            <!-- 优惠券单元格 -->
            <van-coupon-cell
              :coupons="coupons"
              :chosen-coupon="chosenCoupon"
              @click="showList = true"
            />
          </van-cell-group>
      </div>
      <!-- 优惠券列表 -->
      <van-popup class="discount-list" v-model="showList" position="bottom">
        <van-coupon-list
            :coupons="coupons"
            :chosen-coupon="chosenCoupon"
            :disabled-coupons="disabledCoupons"
            :show-exchange-bar="false"
            @change="onChange"
            @exchange="onExchange"
        />
      </van-popup>
      <!-- 支付 -->
      <div class="order-pay">
        <van-submit-bar
            :loading="loading"
            :price="total_pay*100"
            button-text="立即支付"
            @submit="pay"
        />
      </div>
      <back :scroll="false"></back>
  </div>
</template>

<script>
import back from '../../components/base/back.vue'
export default {
  name: 'order-person',
  comments: 'order-person',
  components: {
    back
  },
  data () {
    return {
      course: {},
      origin_price: 0,
      count: 5,
      loading: false,
      showList: false,
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: []
    }
  },
  computed: {
    // 合计总价
    total_pay: {
      get: function () {
        var price = this.origin_price * this.count
        var couponValue = 0
        if (this.chosenCoupon !== -1) {
          couponValue = this.coupons[this.chosenCoupon].value
        }
        return price - couponValue
      },
      set: function () {
      }
    }
  },
  created () {
    if (localStorage.reload === 'done') {
      document.title = '订单确认'
      this.getCourse()
      this.getCoupons()
      localStorage.reload = ''
    } else {
      localStorage.reload = 'done'
      window.location.reload()
    }
  },
  methods: {
    // 选择卡券
    onChange (index) {
      this.showList = false
      this.chosenCoupon = index
      if (index !== -1) {
        this.total_pay = this.origin_price * this.count * 100 - this.coupons[index].value
      } else {
        this.total_pay = this.origin_price * this.count * 100
      }
    },
    // 兑换卡券
    onExchange (code) {
      // this.coupons.push(coupon)
    },
    checkCount () {
      this.count = this.count < 1 ? 1 : this.count
    },
    // 获取课程信息
    getCourse () {
      var that = this
      this.$axios.get('/courses/' + this.$router.history.current.query.course_id).then(response => {
        that.course = response.data
        that.origin_price = response.data.origin_price
        that.total_pay = that.origin_price * that.count * 100
      })
    },
    // 获取卡券
    getCoupons () {
      var that = this
      this.$axios.get('/users/' + JSON.parse(localStorage.user).id + '/coupons?amount=' + that.total_pay).then(response => {
        for (var i = 0; i < response.data.length; i++) {
          var c = {
            available: 1,
            discount: 0,
            denominations: response.data[i].credit * 100,
            origin_condition: response.data[i].limit_condition,
            reason: '',
            value: response.data[i].credit,
            name: response.data[i].name,
            start_at: 1489104000,
            end_at: response.data[i].expired_at
          }
          that.coupons.push(c)
        }
      })
    },
    // 微信支付
    paySubmit: function (info) {
      const ctx = this
      function onBridgeReady () {
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', info,
          function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              ctx.$router.push({
                name: 'appointment'
              })
            }
          }
        )
      }
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
        }
      } else {
        onBridgeReady()
      }
    },
    // 支付确认
    pay: function (e) {
      var that = this
      this.$axios.post('/users/' + JSON.parse(localStorage.user).id + '/orders', {
        amount: that.total_pay,
        real_amount: that.total_pay,
        period: that.count,
        type: 'course',
        course_id: that.course.id
      }).then(response => {
        that.paySubmit(response.data)
      }).catch(error => {
        that.$toast.fail('支付失败！')
        console.log(error)
      })
    }
  }
}
</script>
<style lang="postcss" scoped>
.order{
    width: 100%;
    height: 100%;
    margin-bottom: 50px;
}
.order-form{
    margin: 5px;
}
.order-form>div:first-child{
  border-radius: 4px 4px 0px 0px;
}
.order-form>div:last-child{
  border-radius: 0px 0px 4px 4px;
}
.order-field{
    background-color: #333;
    color: #f8f8f8;
    border-bottom: 1px solid #666;
    text-align: left;
}
.order-field:last-child{
    border-bottom: none;
}
.order-discount{
    margin-top: 10px;
}
.discount-list{
    height: 80%;
}
.order-pay{
    position: fixed;
    bottom: 0px;
    width: 100%;
    z-index: 999;
}
</style>
